package com.example.ai.service.impl;

import com.example.ai.dto.PostDTO;
import com.example.ai.exception.BusinessException;
import com.example.ai.model.Post;
import com.example.ai.model.User;
import com.example.ai.repository.PostRepository;
import com.example.ai.repository.UserRepository;
import com.example.ai.service.PostService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class PostServiceImpl implements PostService {
    private final PostRepository postRepository;
    private final UserRepository userRepository;

    @Override
    public List<PostDTO> getAllPosts() {
        List<Post> posts = postRepository.findAllByOrderByCreateTimeDesc();
        return posts.stream().map(post -> {
            PostDTO dto = new PostDTO();
            BeanUtils.copyProperties(post, dto);
            
            // 获取用户信息
            User user = userRepository.findById(post.getUserId())
                    .orElseThrow(() -> new BusinessException("用户不存在"));
            
            dto.setUsername(user.getUsername());
            dto.setUserAvatar(user.getAvatar());
            
            return dto;
        }).collect(Collectors.toList());
    }
} 